﻿using Newtonsoft.Json;
using System;
using System.Globalization;

namespace DbJobsApi.Extensions
{
    /// <summary>
    /// Decimal的Json格式化转换器
    /// </summary>
    public class DecimalConverter : JsonConverter
    {
        private readonly int _format;
        private readonly int _scale;
        /// <summary>
        /// Decimal的Json格式化转换器
        /// </summary>
        /// <param name="format">保留小数位数，如4</param>
        /// <param name="scale">缩小比例，单位缩小到万，则10000</param>
        public DecimalConverter(int format = 0, int scale = 1)
        {
            _format = format;
            _scale = scale;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType.IsSubclassOf(typeof(double));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value != null)
            {
                if (decimal.TryParse(reader.Value.ToString(), out decimal result))
                    return result;
                else
                    return decimal.Zero;
            }

            return decimal.Zero;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            //writer.WriteValue(string.Format(CultureInfo.InvariantCulture, _format, value));
            var val = (decimal)value;
            if (_scale > 1)
            {
                val /= _scale;
            }
            writer.WriteValue(decimal.Round(val, _format));
        }
    }
}
